package com.ai.imagetext.controller;

import com.ai.imagetext.dto.TagDTO;
import com.ai.imagetext.service.TagService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/api/tags")
@RequiredArgsConstructor
public class TagController {
    
    private final TagService tagService;
    
    /**
     * 获取所有标签
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllTags() {
        log.info("Getting all tags");
        
        try {
            List<TagDTO> tags = tagService.getAllTags();
            
            Map<String, Object> response = createSuccessResponse("获取标签列表成功");
            response.put("data", tags);
            response.put("count", tags.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get all tags failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 根据分类获取标签
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<Map<String, Object>> getTagsByCategory(@PathVariable String category) {
        log.info("Getting tags by category: {}", category);
        
        try {
            List<TagDTO> tags = tagService.getTagsByCategory(category);
            
            Map<String, Object> response = createSuccessResponse("根据分类获取标签成功");
            response.put("data", tags);
            response.put("category", category);
            response.put("count", tags.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get tags by category failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 搜索标签
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchTags(@RequestParam String keyword) {
        log.info("Searching tags with keyword: {}", keyword);
        
        try {
            List<TagDTO> tags = tagService.searchTags(keyword);
            
            Map<String, Object> response = createSuccessResponse("搜索标签成功");
            response.put("data", tags);
            response.put("keyword", keyword);
            response.put("count", tags.size());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Search tags failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取热门标签
     */
    @GetMapping("/popular")
    public ResponseEntity<Map<String, Object>> getPopularTags(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        log.info("Getting popular tags: page={}, size={}", page, size);
        
        try {
            Page<TagDTO> tagPage = tagService.getPopularTags(page, size);
            
            Map<String, Object> response = createSuccessResponse("获取热门标签成功");
            response.put("data", tagPage.getContent());
            response.put("pagination", createPaginationInfo(tagPage));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get popular tags failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取最新标签
     */
    @GetMapping("/latest")
    public ResponseEntity<Map<String, Object>> getLatestTags(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        log.info("Getting latest tags: page={}, size={}", page, size);
        
        try {
            Page<TagDTO> tagPage = tagService.getLatestTags(page, size);
            
            Map<String, Object> response = createSuccessResponse("获取最新标签成功");
            response.put("data", tagPage.getContent());
            response.put("pagination", createPaginationInfo(tagPage));
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get latest tags failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取标签
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getTagById(@PathVariable Long id) {
        log.info("Getting tag by ID: {}", id);
        
        try {
            Optional<TagDTO> tag = tagService.getTagById(id);
            
            if (tag.isPresent()) {
                Map<String, Object> response = createSuccessResponse("获取标签详情成功");
                response.put("data", tag.get());
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.notFound().build();
            }
            
        } catch (Exception e) {
            log.error("Get tag by ID failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 根据名称获取标签
     */
    @GetMapping("/name/{name}")
    public ResponseEntity<Map<String, Object>> getTagByName(@PathVariable String name) {
        log.info("Getting tag by name: {}", name);
        
        try {
            Optional<TagDTO> tag = tagService.getTagByName(name);
            
            if (tag.isPresent()) {
                Map<String, Object> response = createSuccessResponse("根据名称获取标签成功");
                response.put("data", tag.get());
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.notFound().build();
            }
            
        } catch (Exception e) {
            log.error("Get tag by name failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 创建标签
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createTag(@RequestBody TagDTO tagDTO) {
        log.info("Creating tag: {}", tagDTO.getName());
        
        try {
            TagDTO createdTag = tagService.createTag(tagDTO);
            
            Map<String, Object> response = createSuccessResponse("创建标签成功");
            response.put("data", createdTag);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Create tag failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 更新标签
     */
    @PostMapping("/{id}/update")
    public ResponseEntity<Map<String, Object>> updateTag(@PathVariable Long id, @RequestBody TagDTO tagDTO) {
        log.info("Updating tag: {}", id);
        
        try {
            TagDTO updatedTag = tagService.updateTag(id, tagDTO);
            
            Map<String, Object> response = createSuccessResponse("更新标签成功");
            response.put("data", updatedTag);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Update tag failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 删除标签
     */
    @PostMapping("/{id}/delete")
    public ResponseEntity<Map<String, Object>> deleteTag(@PathVariable Long id) {
        log.info("Deleting tag: {}", id);
        
        try {
            tagService.deleteTag(id);
            
            Map<String, Object> response = createSuccessResponse("删除标签成功");
            response.put("tagId", id);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Delete tag failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 获取标签统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getTagStatistics() {
        log.info("Getting tag statistics");
        
        try {
            TagService.TagStatistics stats = tagService.getTagStatistics();
            
            Map<String, Object> response = createSuccessResponse("获取标签统计信息成功");
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("Get tag statistics failed", e);
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }
    
    /**
     * 创建分页信息
     */
    private Map<String, Object> createPaginationInfo(Page<?> page) {
        Map<String, Object> pagination = new HashMap<>();
        pagination.put("currentPage", page.getNumber());
        pagination.put("totalPages", page.getTotalPages());
        pagination.put("totalElements", page.getTotalElements());
        pagination.put("size", page.getSize());
        pagination.put("hasNext", page.hasNext());
        pagination.put("hasPrevious", page.hasPrevious());
        return pagination;
    }
    
    /**
     * 创建成功响应
     */
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }
}